package models

import "gorm.io/gorm"

type Novels struct {
	gorm.Model
	Title  string `gorm:"type:varchar(100)" json:"title"`
	Img    string `gorm:"type:varchar(255)" json:"img"`
	Commit string `gorm:"type:varchar(100)" json:"commit"`
	Info   string `gorm:"type:varchar(100)" json:"info"`
}

// 添加
func (u *Novels) Create() error {
	return DB.Create(&u).Error
}
func (u *Novels) Update() error {
	return DB.Updates(&u).Error
}

// 查找
func (u *Novels) Find() error {
	return DB.Where("id = ?", u.ID).Limit(1).Find(&u).Error
}

// 删除
func (u *Novels) Del() error {
	return DB.Delete(&u).Error
}
func (u *Novels) List(keyword string, page, pageSize, typeId int) (list []*Novels, err error) {
	db := DB
	if typeId > 0 {
		db = db.Where("type_id = ?", typeId)
	}
	err = DB.Where("title like ?", "%"+keyword+"%").Scopes(Paginate(page, pageSize)).Find(&list).Error
	return
}

func Paginate(page, pageSize int) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {

		if page <= 0 {
			page = 1
		}

		switch {
		case pageSize > 100:
			pageSize = 100
		case pageSize <= 0:
			pageSize = 10
		}

		offset := (page - 1) * pageSize
		return db.Offset(offset).Limit(pageSize)
	}
}
